﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Reviewer.Entities;
using Reviewer.Business;
using Reviewer.Entities.Services;
using System.Globalization;
using System.Collections.ObjectModel;

public partial class V2Controls_Top10SpilViews : System.Web.UI.UserControl
{
    private delegate Collection<GameView> LoadGameViewsDelegate();
    private LoadGameViewsDelegate loadHandler;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Page.AddOnPreRenderCompleteAsync(
                new BeginEventHandler(this.BeginAsyncLoad),
                new EndEventHandler(this.EndAsyncLoad)
                );
        }
    }

    private IAsyncResult BeginAsyncLoad(object sender, EventArgs e, AsyncCallback cb, object state)
    {
        this.loadHandler = new LoadGameViewsDelegate(LoadGameViews);
        return this.loadHandler.BeginInvoke(cb, state);
    }

    private void EndAsyncLoad(IAsyncResult ar)
    {
        Collection<GameView> views = this.loadHandler.EndInvoke(ar);
        if (views.Count == 0)
        {
            this.Visible = false;
        }
        else
        {
            this.uiRepViews.DataSource = views;
            this.uiRepViews.DataBind();
        }
    }

    private Collection<GameView> LoadGameViews()
    {
        using (IGameViewService gameViewService = ServiceFactory.GameViewService)
        {
            try
            {
                return gameViewService.FindTopBy(DateTime.Today, 10);
            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine(err.ToString());
            }
        }
        return null;
    }

    protected void uiRepViews_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        switch (e.Item.ItemType)
        {
            case ListItemType.AlternatingItem:
            case ListItemType.Item:
                GameView gameView = e.Item.DataItem as GameView;
                HyperLink link = e.Item.FindControl("uiHlItem") as HyperLink;
                link.NavigateUrl = UrlUtillity.GetGameUri(gameView.GameTitle, gameView.GameFormatName);
                link.Text = String.Format(CultureInfo.InvariantCulture
                    , "{0}# {1}<br />{2}"
                    , e.Item.ItemIndex + 1
                    , gameView.GameTitle
                    , gameView.GameFormatName);
                break;

        }
    }
}
